//
//  KaijiangViewController.m
//  DaleTou
//
//  Created by hejingjin on 2018/5/27.
//  Copyright © 2018年 geren. All rights reserved.
//

#import "KaijiangViewController.h"
#import "Appearance.h"
#import "DaleTouModel.h"
#import "KaiJIangListCell.h"
#import "KaiJiangDetailViewController.h"
#import <MJRefresh/MJRefresh.h>
#import "MQRequestTools.h"
#import "MBProgressHUD+MJ.h"
@interface KaijiangViewController ()<UITableViewDelegate,UITableViewDataSource>

@property(nonatomic,strong)UITableView *tableview;
@property(nonatomic,strong)NSMutableArray *dataSource;
@property(nonatomic,assign)NSInteger currentcount;

@end


@implementation KaijiangViewController


-(NSMutableArray *)dataSource{
    if (!_dataSource) {
        _dataSource = [NSMutableArray array];
    }
    return _dataSource;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.view.backgroundColor = [UIColor colorWithHexString:@"ffffff"];
    [self setNavConfigStartColor:@"#ff8e01" endColor:@"#ff8e01"];
    [self ApptitileView:@"开奖"];
    
    if (@available(iOS 11.0, *)) {
        self.tableview.contentInsetAdjustmentBehavior = UIApplicationBackgroundFetchIntervalNever;
    }else {
        self.automaticallyAdjustsScrollViewInsets = NO;
    }
    
    int x = arc4random()%1200+181329;
    self.currentcount = x;
    
//
//
//    for (int i = 0; i<15; i++) {
//        DaleTouModel *model = [DaleTouModel new];
//        NSMutableArray *readArray = [NSMutableArray array];
//        NSMutableArray *blueArray = [NSMutableArray array];
//        while (readArray.count<5) {
//            int x = arc4random()%35 +1;
//            NSNumber *number = [NSNumber numberWithInteger:x];
//            if (![readArray containsObject:number]) {
//                [readArray addObject:number];
//            }
//        }
//        while (blueArray.count<2) {
//            int x = arc4random()%12 +1;
//            NSNumber *number = [NSNumber numberWithInteger:x];
//            if (![blueArray containsObject:number]) {
//                [blueArray addObject:number];
//            }
//        }
//        model.redarray = [readArray mutableCopy];
//        model.bluearray = [blueArray mutableCopy];
//        [self.dataSource addObject:model];
//    }
      [self.view addSubview:self.tableview];
    
    
    self.tableview.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        
        [self loadData];
    }];
    [self loadData];
    [self.tableview reloadData];
    
}


-(void)loadData{
    
    [self.dataSource removeAllObjects];
    
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    //获取完整路径
    NSString *documentsDirectory = [paths objectAtIndex:0];
    
    NSString *plistPath = [documentsDirectory stringByAppendingPathComponent:@"kaijiang.plist"];//这里就是你将要存储的沙盒路径（.plist文件，名字自定义）
    NSMutableArray *datearray = [[NSMutableArray alloc] initWithContentsOfFile:plistPath];
    if (datearray.count>0) {
        for (NSDictionary * dic in datearray) {
            DaleTouModel *model = [DaleTouModel new];
            model.redarray = [NSMutableArray array];
            model.bluearray = [NSMutableArray array];
            NSString *numberstr = [dic valueForKey:@"preDrawCode"];
            NSString *timestr = [dic valueForKey:@"preDrawTime"];
            NSString *qishu = [dic valueForKey:@"preDrawIssue"];
            model.qishu = qishu;
            model.timestr = [timestr substringWithRange:NSMakeRange(0, 10)];
            NSArray *allnumberarr = [numberstr componentsSeparatedByString:@","];
            if (allnumberarr.count==7) {
                NSArray *readarray = [allnumberarr subarrayWithRange:NSMakeRange(0, 5)];
                NSArray *bulearray = [allnumberarr subarrayWithRange:NSMakeRange(5, 2)];
                for (NSString *str in readarray) {
                    NSNumber *number = [NSNumber numberWithInteger:[str integerValue]];
                    [model.redarray addObject:number];
                }
                for (NSString *str in bulearray) {
                    NSNumber *number = [NSNumber numberWithInteger:[str integerValue]];
                    [model.bluearray addObject:number];
                }
                [self.dataSource addObject:model];
            }
            
           
        }
        [self.tableview reloadData];
        [self.tableview.mj_header endRefreshing];
        return;
    }
 

    
    MQRequestTools *tools = [MQRequestTools sharedInstance];
    [tools.sessionManager POST:@"https://api.api68.com/QuanGuoCai/getHistoryLotteryInfo.do?lotCode=10040" parameters:nil progress:^(NSProgress * _Nonnull downloadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        
        NSDictionary *result = [responseObject valueForKey:@"result"];
        NSArray *datearray = [result valueForKey:@"data"];
        for (NSDictionary *dic in datearray) {
            DaleTouModel *model = [DaleTouModel new];
            model.redarray = [NSMutableArray array];
            model.bluearray = [NSMutableArray array];
            NSString *numberstr = [dic valueForKey:@"preDrawCode"];
            NSString *timestr = [dic valueForKey:@"preDrawTime"];
            NSString *qishu = [dic valueForKey:@"preDrawIssue"];
            model.qishu = qishu;
            model.timestr = [timestr substringWithRange:NSMakeRange(0, 10)];
            NSArray *allnumberarr = [numberstr componentsSeparatedByString:@","];
            if (allnumberarr.count==7) {
                NSArray *readarray = [allnumberarr subarrayWithRange:NSMakeRange(0, 5)];
                NSArray *bulearray = [allnumberarr subarrayWithRange:NSMakeRange(5, 2)];
                for (NSString *str in readarray) {
                    NSNumber *number = [NSNumber numberWithInteger:[str integerValue]];
                    [model.redarray addObject:number];
                }
                for (NSString *str in bulearray) {
                    NSNumber *number = [NSNumber numberWithInteger:[str integerValue]];
                    [model.bluearray addObject:number];
                }
            }
            [self.dataSource addObject:model];
        }
            [self.tableview reloadData];
            [self.tableview.mj_header endRefreshing];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            [MBProgressHUD showError:@"请求失败"];
            [self.tableview.mj_header endRefreshing];
    }];
    
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.dataSource.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 90;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    KaiJIangListCell *cell = [KaiJIangListCell cellWithTableView:tableView];
    DaleTouModel *model = self.dataSource[indexPath.row];
    if (indexPath.row==0) {
        cell.idimageview.hidden = NO;
        for (UIButton *btn in cell.numberBtnArray) {
            btn.layer.cornerRadius = 15.f;
            btn.layer.borderWidth =0.f;
            btn.layer.borderColor = [UIColor colorWithHexString:@"ffffff"].CGColor;
            [btn setTitleColor:[UIColor colorWithHexString:@"fffffff"] forState:UIControlStateNormal];
            NSInteger tag = btn.tag;
            if (tag<5) {
//                FF8E01
//                6E75CB
                 [btn setBackgroundColor:[UIColor colorWithHexString:@"FF8E01"]];
            }else{
                 [btn setBackgroundColor:[UIColor colorWithHexString:@"6E75CB"]];
            }
        }
    }else{
        cell.idimageview.hidden = YES;
        
        for (UIButton *btn in cell.numberBtnArray) {
            btn.layer.cornerRadius = 15.f;
            btn.layer.borderWidth =1.f;
            btn.layer.borderColor = [UIColor colorWithHexString:@"efefef"].CGColor;
            [btn setBackgroundColor:[UIColor colorWithHexString:@"ffffff"]];
            
            NSInteger tag = btn.tag;
            if (tag<5) {
                   [btn setTitleColor:[UIColor colorWithHexString:@"FF8E01"] forState:UIControlStateNormal];
            }else{
                   [btn setTitleColor:[UIColor colorWithHexString:@"6E75CB"] forState:UIControlStateNormal];
            }
        }
    }
    for (UIButton *btm in cell.numberBtnArray) {
        NSInteger tag = btm.tag;
        if (tag<5) {
            if (model.redarray.count>tag) {
                [btm setTitle:[NSString stringWithFormat:@"%@",model.redarray[tag]] forState:UIControlStateNormal];
            }
        }else{
            if (model.bluearray.count>tag-5) {
                [btm setTitle:[NSString stringWithFormat:@"%@",model.bluearray[tag -5]] forState:UIControlStateNormal];
            }
        }
    }
    cell.orderNumberLabel.text = [NSString stringWithFormat:@"第%@期",model.qishu];
    cell.timeLabel.text = [NSString stringWithFormat:@"%@", model.timestr];
    return cell;
    
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
      DaleTouModel *model = self.dataSource[indexPath.row];
    KaiJiangDetailViewController *vc = [[KaiJiangDetailViewController alloc] init];
    vc.hidesBottomBarWhenPushed = YES;
    vc.model = model;
    vc.timestrs = [NSString stringWithFormat:@"2018-05-%ld",29-indexPath.row];
    vc.numberorder = self.currentcount - indexPath.row;
    [self.navigationController pushViewController:vc animated:YES];
}


-(UITableView *)tableview{
    if (!_tableview) {
        CGRect frame = CGRectMake(0,NAV_HEIGHT, Main_Screen_Width, Main_Screen_Height-NAV_HEIGHT-TABBAR_HEIGHT);
        _tableview = [[UITableView alloc] initWithFrame:frame style:UITableViewStylePlain];
        _tableview.delegate = self;
        _tableview.dataSource = self;
        _tableview.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableview.estimatedRowHeight = 0;
        _tableview.backgroundColor = [UIColor colorWithHexString:@"f4f4f4"];
        _tableview.estimatedSectionFooterHeight = 0;
        _tableview.estimatedSectionHeaderHeight = 0;
        _tableview.showsVerticalScrollIndicator = NO;
    }
    return _tableview;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
